#include "robotfilemgri.h"
#include "tmglobaldef.h"

RobotFileMgrI::RobotFileMgrI()
{
    m_strDirPath = g_pSettingCore->value("File/RootDir", "D:/RootDir").toString();
    if( m_strDirPath.length()>0 ){
        QDir uprootDir(m_strDirPath);
        uprootDir.mkpath(m_strDirPath);
    }
}

std::string RobotFileMgrI::GetDirPath(const Ice::Current &)
{
    std::string strPath = m_strDirPath.toUtf8().toStdString();
    return strPath;
}

void RobotFileMgrI::List(Ice::StringSeq &sList, const Ice::Current &)
{
    sList.clear();
    QDir rootDir(m_strDirPath);
    QStringList strFileList = rootDir.entryList(QDir::Files|QDir::NoDotAndDotDot);
    foreach (QString oneName, strFileList) {
        std::string strName = oneName.toUtf8().toStdString();
        sList.push_back(strName);
    }
}

void RobotFileMgrI::Delete(const std::string &strFullName, const Ice::Current &)
{
    QString strFullPath = QString("%1/%2").arg(m_strDirPath).arg(QString::fromUtf8(strFullName.c_str()));
    QFile curFile(strFullPath);
    if( curFile.exists() ){
        curFile.remove();
    }
}

bool RobotFileMgrI::SendFile(Ice::Int nHandle, const Ice::ByteSeq &bSeq, bool bEnd, const Ice::Current &)
{
    if( nHandle > 0 ){
        FILE* pHandle = (FILE*)nHandle;
//        qDebug()<<"SendFile:"<<nHandle<<bSeq.size()<<bEnd;
        if(bSeq.size()>0){
            const char* pData = (const char*)bSeq.data();
            fwrite(pData, 1, bSeq.size(), pHandle);
            fflush(pHandle);
        }
        if( bEnd ){
//            qDebug()<<"SendFile:"<<pHandle;
            fclose(pHandle);
        }
        return true;
    }
    return false;
}

Ice::Int RobotFileMgrI::SendStart(const std::string &strFullName, const Ice::Current &)
{
    QString strFullPath = QString("%1/%2").arg(m_strDirPath).arg(QString::fromUtf8(strFullName.c_str()));
    strFullPath = QDir::fromNativeSeparators(strFullPath);
//    qDebug()<<"fopen:"<<strFullPath;
    static QTextCodec* pCodec = QTextCodec::codecForName("GB18030");
    FILE* pHandle = fopen(pCodec->fromUnicode(strFullPath).data(), "wb");
    qDebug()<<"fopen:"<<pHandle<<(int)pHandle<<strFullName.c_str();
    return (int)pHandle;
}




